import type {
	DataProps,
	FormInstance,
	NameProps,
	ReducerAction,
	ConfigWayProps
} from '../interface';

class FormStore {
	store: DataProps = {}; // 管理表单的整体数据
	update_store: DataProps = {}; // 保存更新的对象
	initialValues: DataProps = {}; // 保存初始值
	configWays: ConfigWayProps = {}; // 收录对应的方法集合

	// 用于暴露方法
	public getDetail = (): FormInstance => ({
		getFieldValue: this.getFieldValue,
		dispatch: this.dispatch,
		unRegisterField: this.unRegisterField,
		registerField: this.registerField,
		setConfigWays: this.setConfigWays, // 设置方法区间
		submit: this.submit, // 用于表单提交
		resetFields: this.resetFields // 重置表单
	});

	// 注册表单方法
	registerField = (name: NameProps, updateChange: DataProps) => {
		this.update_store[name] = updateChange;
	};

	// 卸载表单方法
	unRegisterField = (name: NameProps) => {
		delete this.update_store[name];
	};

	setConfigWays = (configWays: ConfigWayProps) => {
		this.configWays = configWays;
	};

	// 获取对应的值
	getFieldValue = (name: NameProps) => {
		return this.store[name];
	};

	// 触发更新
	dispatch = (action: ReducerAction) => {
		switch (action.type) {
			case 'updateValue': {
				const { name, value } = action;
				this.updateValue(name, value);
				break;
			}
			default:
		}
	};

	// 更新
	updateValue = (name: NameProps, value: any) => {
		this.store = {
			...this.store,
			[name]: value
		};
		// this.updateStoreField(name)
	};

	// 更新对应的表单
	updateStoreField = (name: NameProps) => {
		const update = this.update_store[name];
		if (update) update?.updateValue();
	};

	// 用于表单提交
	submit = () => {
		const { onFinish } = this.configWays;

		onFinish && onFinish(this.store);
	};

	// 重置表单
	resetFields = () => {
		const { onReset } = this.configWays;
		Object.keys(this.store).forEach((key) => {
			// 重置表单的时候，如果有初始值，就用初始值，没有就删除
			this.initialValues[key]
				? (this.store[key] = this.initialValues[key])
				: delete this.store[key];
			this.updateStoreField(key);
		});
		onReset && onReset();
	};
}

export default FormStore;
